<?php
/**
 * Login
 */
class Login extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->helper('url');
        if (file_exists('application/controllers/install.php'))
            redirect('install');
        $this->load->model('user_model');
        $this->load->library('session');
    }

    function index() {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $this->form_validation->set_rules('username', '用户名', 'trim||required|xss_clean');
        $this->form_validation->set_rules('password', '密码', 'trim|required|xss_clean|md5');

        $data['title'] = '登录';
        $data['error'] = '';    // if not post , no error

        if (isset($this->session->userdata['login'])) {
            redirect('poster_admin/index');
        }

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('poster_admin/login', $data);
        } else {
            $query = $this->user_model->login();
            if (empty($query)) {
                $data['error'] = '用户名或密码错误';
                $this->load->view('poster_admin/login', $data);
            } else {
                // Write username, level, login to the session
                $newdata = array(
                    'username' => $query['username'],
                    'level' => $query['level'],
                    'login' => TRUE
                );
                $this->session->set_userdata($newdata);
                redirect('poster_admin');
            }
        }
    }
}